// 教材大纲数据模型
class CurriculumOutline {
  final String id;
  final String title;
  final String subject;
  final String grade;
  final String volume;
  final List<Chapter> chapters;
  final String? description;
  final DateTime? createTime;
  final DateTime? updateTime;
  final int? level;
  final String? parentId;
  final int? sortOrder;

  CurriculumOutline({
    required this.id,
    required this.title,
    required this.subject,
    required this.grade,
    required this.volume,
    required this.chapters,
    this.description,
    this.createTime,
    this.updateTime,
    this.level,
    this.parentId,
    this.sortOrder,
  });

  factory CurriculumOutline.fromJson(Map<String, dynamic> json) {
    // API返回的是知识点列表，需要转换为教材大纲结构
    return CurriculumOutline(
      id: json['id']?.toString() ?? '',
      title: json['title']?.toString() ?? '',
      subject: json['subject']?.toString() ?? '',
      grade: json['grade']?.toString() ?? '',
      volume: json['volume']?.toString() ?? '',
      chapters: [], // 暂时为空，后续需要根据parentId构建章节结构
      description: json['knowledgePoint']?.toString(), // 使用knowledgePoint作为描述
      level: json['level']?.toInt(),
      parentId: json['parentId']?.toString(),
      sortOrder: json['sortOrder']?.toInt(),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'subject': subject,
      'grade': grade,
      'volume': volume,
      'chapters': chapters.map((e) => e.toJson()).toList(),
      'description': description,
      'createTime': createTime?.toIso8601String(),
      'updateTime': updateTime?.toIso8601String(),
      'level': level,
      'parentId': parentId,
      'sortOrder': sortOrder,
    };
  }

  @override
  String toString() {
    return 'CurriculumOutline(id: $id, title: $title, subject: $subject, grade: $grade, volume: $volume, chapters: ${chapters.length}, level: $level)';
  }
}

// 章节数据模型
class Chapter {
  final String id;
  final String title;
  final int order;
  final List<KnowledgePoint> knowledgePoints;
  final String? description;
  final int? difficulty;

  Chapter({
    required this.id,
    required this.title,
    required this.order,
    required this.knowledgePoints,
    this.description,
    this.difficulty,
  });

  factory Chapter.fromJson(Map<String, dynamic> json) {
    return Chapter(
      id: json['id']?.toString() ?? '',
      title: json['title']?.toString() ?? '',
      order: json['order']?.toInt() ?? 0,
      knowledgePoints:
          (json['knowledgePoints'] as List<dynamic>?)
              ?.map((e) => KnowledgePoint.fromJson(e as Map<String, dynamic>))
              .toList() ??
          [],
      description: json['description']?.toString(),
      difficulty: json['difficulty']?.toInt(),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'order': order,
      'knowledgePoints': knowledgePoints.map((e) => e.toJson()).toList(),
      'description': description,
      'difficulty': difficulty,
    };
  }

  @override
  String toString() {
    return 'Chapter(id: $id, title: $title, order: $order, knowledgePoints: ${knowledgePoints.length})';
  }
}

// 知识点数据模型
class KnowledgePoint {
  final String id;
  final String title;
  final String description;
  final int difficulty;
  final int order;
  final String? chapterId;
  final List<String>? tags;

  KnowledgePoint({
    required this.id,
    required this.title,
    required this.description,
    required this.difficulty,
    required this.order,
    this.chapterId,
    this.tags,
  });

  factory KnowledgePoint.fromJson(Map<String, dynamic> json) {
    return KnowledgePoint(
      id: json['id']?.toString() ?? '',
      title: json['title']?.toString() ?? '',
      description: json['description']?.toString() ?? '',
      difficulty: json['difficulty']?.toInt() ?? 1,
      order: json['order']?.toInt() ?? 0,
      chapterId: json['chapterId']?.toString(),
      tags: (json['tags'] as List<dynamic>?)?.map((e) => e.toString()).toList(),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'description': description,
      'difficulty': difficulty,
      'order': order,
      'chapterId': chapterId,
      'tags': tags,
    };
  }

  // 获取难度等级描述
  String get difficultyText {
    switch (difficulty) {
      case 1:
        return '简单';
      case 2:
        return '中等';
      case 3:
        return '困难';
      default:
        return '未知';
    }
  }

  // 获取难度颜色
  int get difficultyColor {
    switch (difficulty) {
      case 1:
        return 0xFF4CAF50; // 绿色
      case 2:
        return 0xFFFF9800; // 橙色
      case 3:
        return 0xFFF44336; // 红色
      default:
        return 0xFF9E9E9E; // 灰色
    }
  }

  @override
  String toString() {
    return 'KnowledgePoint(id: $id, title: $title, difficulty: $difficulty)';
  }
}

// API响应模型
class CurriculumApiResponse {
  final bool success;
  final String? message;
  final List<CurriculumOutline>? data;
  final int? code;

  CurriculumApiResponse({
    required this.success,
    this.message,
    this.data,
    this.code,
  });

  factory CurriculumApiResponse.fromJson(Map<String, dynamic> json) {
    final code = json['code']?.toInt();
    final success = code == 200; // 根据code判断是否成功

    List<CurriculumOutline>? curriculumData;
    if (success && json['data'] != null) {
      final rawData = json['data'] as List<dynamic>;
      final items =
          rawData
              .map((e) => CurriculumOutline.fromJson(e as Map<String, dynamic>))
              .toList();

      // 构建树形结构
      curriculumData = _buildTreeStructure(items);
    }

    return CurriculumApiResponse(
      success: success,
      message:
          json['msg']?.toString() ?? json['message']?.toString(), // 优先使用msg字段
      data: curriculumData,
      code: code,
    );
  }

  /// 构建树形结构
  static List<CurriculumOutline> _buildTreeStructure(
    List<CurriculumOutline> items,
  ) {
    // 按level和sortOrder排序
    items.sort((a, b) {
      if (a.level != b.level) {
        return (a.level ?? 0).compareTo(b.level ?? 0);
      }
      return (a.sortOrder ?? 0).compareTo(b.sortOrder ?? 0);
    });

    // 创建ID到项目的映射
    final Map<String, CurriculumOutline> itemMap = {};
    for (final item in items) {
      itemMap[item.id] = item;
    }

    // 构建完整的树形结构
    return _buildCompleteTree(items, itemMap);
  }

  /// 构建完整的树形结构
  static List<CurriculumOutline> _buildCompleteTree(
    List<CurriculumOutline> items,
    Map<String, CurriculumOutline> itemMap,
  ) {
    final List<CurriculumOutline> rootItems = [];
    final Map<String, List<Chapter>> chapterMap = {};

    // 第一步：为每个节点创建章节映射
    for (final item in items) {
      if (!chapterMap.containsKey(item.id)) {
        chapterMap[item.id] = [];
      }
    }

    // 第二步：建立父子关系 - 处理Level 1到Level 2的关系
    for (final item in items) {
      if (item.parentId == null || item.parentId!.isEmpty) {
        // 根节点（Level 1）- 教材总目录
        rootItems.add(item);
      } else {
        // 子节点 - 根据level判断层级关系
        final parentId = item.parentId!;
        if (chapterMap.containsKey(parentId)) {
          final chapter = Chapter(
            id: item.id,
            title: item.title,
            order: item.sortOrder ?? 0,
            knowledgePoints: [], // 暂时为空，后续填充
            description: item.description,
            difficulty: 1,
          );
          chapterMap[parentId]!.add(chapter);
        }
      }
    }

    // 第三步：递归填充子章节的知识点 - 处理Level 2到Level 3，Level 3到Level 4的关系
    for (final item in items) {
      if (chapterMap.containsKey(item.id) && chapterMap[item.id]!.isNotEmpty) {
        // 为每个章节填充其子知识点
        for (final chapter in chapterMap[item.id]!) {
          // 查找当前章节的直接子节点
          final childItems =
              items.where((i) => i.parentId == chapter.id).toList();

          // 将子节点转换为知识点
          chapter.knowledgePoints.addAll(
            childItems.map(
              (child) => KnowledgePoint(
                id: child.id,
                title: child.title,
                description: child.description ?? '',
                difficulty: 1,
                order: child.sortOrder ?? 0,
                chapterId: chapter.id,
              ),
            ),
          );
        }
      }
    }

    // 第四步：更新根节点的章节列表
    for (final rootItem in rootItems) {
      final updatedRoot = CurriculumOutline(
        id: rootItem.id,
        title: rootItem.title,
        subject: rootItem.subject,
        grade: rootItem.grade,
        volume: rootItem.volume,
        chapters: chapterMap[rootItem.id] ?? [],
        description: rootItem.description,
        createTime: rootItem.createTime,
        updateTime: rootItem.updateTime,
        level: rootItem.level,
        parentId: rootItem.parentId,
        sortOrder: rootItem.sortOrder,
      );

      final index = rootItems.indexOf(rootItem);
      rootItems[index] = updatedRoot;
    }

    return rootItems;
  }

  @override
  String toString() {
    return 'CurriculumApiResponse(success: $success, message: $message, data: ${data?.length ?? 0})';
  }
}
